package com.xinghanlaser.applet.base.auth.security.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinghanlaser.applet.base.common.entity.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.xinghanlaser.applet.base.common.enums.ResponseCodeEnum.UN_AUTH;

/**
 * @author dym
 * @date 2019-09-19 16:24
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");

        if (exception instanceof BadCredentialsException) {
            response.getWriter().print(objectMapper.writeValueAsString(ResponseEntity.fault(UN_AUTH, "用户名或密码错误")));
        }
        else if (exception instanceof UsernameNotFoundException) {
            response.getWriter().print(objectMapper.writeValueAsString(ResponseEntity.fault(UN_AUTH, "用户不存在")));
        }
        else if (exception instanceof DisabledException) {
            response.getWriter().print(objectMapper.writeValueAsString(ResponseEntity.fault(UN_AUTH,"用户被禁用,请联系管理员处理")));
        }
        else {
            response.getWriter().print(objectMapper.writeValueAsString(ResponseEntity.fault(UN_AUTH,"认证失败")));
        }

    }
}
